package com.service;

import com.entity.OrderList;
import com.entity.Product;
import com.entity.Shop;
import com.strages.product.DefaultStrage;
import com.strages.product.Strage;
import com.strages.sum.DefaultSumStrage;
import com.strages.sum.SumStrage;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ShopService {

    private Shop shop;

    private Map<Class<? extends Product>, Strage> strageMap;

    private Strage defaultStrage;

    private SumStrage sumStrage;

    public ShopService(Shop shop) {
        this.shop = shop;
        strageMap = new HashMap<>();
        defaultStrage = new DefaultStrage();
        sumStrage = new DefaultSumStrage();
    }

    public BigDecimal sell(OrderList orderList) {
        Map<Class<? extends Product>, BigDecimal> map = new HashMap<>();
        Map<Class<? extends Product>, BigDecimal> orders = orderList.getList();
        Iterator<Class<? extends Product>> iterator = orders.keySet().iterator();
        while (iterator.hasNext()) {
            Class<? extends Product> pClass = iterator.next();
            Product p = shop.getProduct(pClass);
            BigDecimal count = orders.get(pClass);
            if (strageMap.containsKey(pClass)) {
                map.put(pClass, strageMap.get(pClass).cal(p.getPrice(), count));
            } else {
                map.put(pClass, defaultStrage.cal(p.getPrice(), count));
            }
        }
        return sumStrage.cal(map);
    }

    public void addStrage(Class<? extends Product> clazz, Strage strage) {
        strageMap.put(clazz, strage);
    }

    public void delStrage(Class<? extends Product> clazz) {
        strageMap.remove(clazz);
    }

    public void setDefaultStrage(Strage strage) {
        this.defaultStrage = strage;
    }

    public void setSumStrage(SumStrage sumStrage) {
        this.sumStrage = sumStrage;
    }
}
